/*
从文件读取配置信息
*/
package mainfuncs

import (
	"errors"
	"fmt"

	"LogManagementSystem/logagent/tailf"

	"github.com/astaxie/beego/config"
)

var (
	AppConfig *Config //配置信息对象
)

//Config 存储从文件中读取的配置信息
type Config struct {
	LogLevel string
	LogPath  string

	ChanSize    int
	KafkaAddr   string
	CollectConf []tailf.CollectConf

	EtcdAddr string
	EtcdKey  string
}

//loadCollectConf 从配置信息读取要收集日志的路径等kafka相关配置
func loadCollectConf(conf config.Configer) (err error) {

	var cc tailf.CollectConf
	cc.LogPath = conf.String("collect::log_path")
	if len(cc.LogPath) == 0 {
		err = errors.New("invalid collect::log_path")
		return
	}

	cc.Topic = conf.String("collect::topic")
	if len(cc.LogPath) == 0 {
		err = errors.New("invalid collect::topic")
		return
	}

	AppConfig.CollectConf = append(AppConfig.CollectConf, cc)
	return
}

//LoadConf 读取配置文件，获取配置信息
func LoadConf(confType, filename string) (err error) {

	conf, err := config.NewConfig(confType, filename)
	if err != nil {
		fmt.Println("new config failed, err:", err)
		return
	}

	AppConfig = &Config{}

	AppConfig.LogLevel = conf.String("logs::log_level")
	if len(AppConfig.LogLevel) == 0 {
		AppConfig.LogLevel = "debug"
	}

	AppConfig.LogPath = conf.String("logs::log_path")
	if len(AppConfig.LogPath) == 0 {
		AppConfig.LogPath = "./logs"
	}

	AppConfig.ChanSize, err = conf.Int("collect::chan_size")
	if err != nil {
		AppConfig.ChanSize = 100
	}

	AppConfig.KafkaAddr = conf.String("kafka::server_addr")
	if len(AppConfig.KafkaAddr) == 0 {
		err = fmt.Errorf("invalid kafka addr")
		return
	}

	AppConfig.EtcdAddr = conf.String("etcd::addr")
	if len(AppConfig.EtcdAddr) == 0 {
		err = fmt.Errorf("invalid etcd addr")
		return
	}

	AppConfig.EtcdKey = conf.String("etcd::configKey")
	if len(AppConfig.EtcdKey) == 0 {
		err = fmt.Errorf("invalid etcd key")
		return
	}

	err = loadCollectConf(conf)
	if err != nil {
		fmt.Printf("load collect conf failed, err:%v\n", err)
		return
	}
	return
}
